package com.yoo.module_base.dialog

import android.annotation.SuppressLint
import android.annotation.TargetApi
import android.content.DialogInterface
import android.content.res.Resources
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.os.Build
import android.os.Bundle
import android.util.Log
import android.util.SparseArray
import android.view.*
import androidx.fragment.app.DialogFragment
import androidx.fragment.app.FragmentManager
import com.yoo.module_base.R
import com.yoo.module_base.dialog.help.DismissListener
import com.yoo.module_base.dialog.help.LogicListener
import com.yoo.module_base.dialog.help.shieldBackScreen


@SuppressLint("NewApi")
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
abstract class CommonBaseDialog : DialogFragment() {

    private companion object {
        const val TAG = "FxCommonBaseDialog_  "
    }


    protected var window: Window? = null
    protected var windowParams: WindowManager.LayoutParams? = null
    var layoutView: View? = null

    override fun onDismiss(dialog: DialogInterface) {
        super.onDismiss(dialog)
        if (dismissCallback() != null) {
            dismissCallback()?.dismissCallback(dialog)
        }
    }

    override fun onStart() {
        super.onStart()

        windowParams?.dimAmount = getDialogOutTransparency()
        windowParams?.gravity = getGravity()
        window?.attributes = windowParams
        if (getDialogCancel()) {
            shieldBackScreen(this)
        } else {
            dialog?.setCanceledOnTouchOutside(true)
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        if (getFullScreen())
            setStyle(STYLE_NORMAL, R.style.MyDialogFullscreen);
        else
            setStyle(STYLE_NORMAL, R.style.MyDialog);
    }

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        beforeLayout()
//        layoutView = inflater.inflate(getLayout(), window?.findViewById(android.R.id.content), false)
        try {
            layoutView = if (getContentView() != null) {
                getContentView()
            } else {
                inflater.inflate(getLayout(), window?.findViewById(android.R.id.content), false)
            }

        } catch (e: Resources.NotFoundException) {
            e.printStackTrace()
        }

        setWindow()
        return layoutView
    }

    /**
     * 设置window 属性
     * */
    private fun setWindow() {
        windowParams = window?.attributes
        windowParams?.windowAnimations = getAnimation()
        window?.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
        layoutView?.layoutParams?.let {
            window?.setLayout(it.width.toInt(), it.height.toInt())
        }

    }


    private fun beforeLayout() {
        window = dialog?.window
        dialog?.requestWindowFeature(Window.FEATURE_NO_TITLE)
        // 设置弹出框本身
        dialog?.window?.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
//
//       window?.setType(WindowManager.LayoutParams.TYPE_APPLICATION_PANEL)
//       window?.setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN)

    }

    /**
     * dialog显示后，处理业务逻辑
     * */
    private fun logic(view: View) {
        val logiclistener = getLogiclistener()
        if (logiclistener != null) {
            logiclistener?.logicCallback(view, this)
        }
    }

    abstract fun getLayout(): Int

    /**
     * 批量设置监听
     * */
    private fun afterLayout(view: View) {
        val views = getViews()
        if (views != null && views.size() > 0) {
            for (it in 0 until views.size()) {
                val keyAt = views.keyAt(it)
                val childView = view?.findViewById<View>(views.keyAt(it))
                if (childView != null && getClickListener() != null)
                    childView.setOnClickListener(getClickListener())
                else
                    Log.i(TAG, "Error ViewId = $keyAt")
            }
        }
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        afterLayout(view)
        logic(view)
    }


    override fun onDestroyView() {
        super.onDestroyView()
        var click = getClickListener()
        if (click != null) {
            click = null
        }
        if (getViews() != null) {
            getViews()!!.clear()
        }
    }


    protected open fun getGravity(): Int? {
        return Gravity.CENTER
    }

    protected open fun getAnimation(): Int? {
        return 0
    }

    protected open fun getDialogCancel(): Boolean {
        return false
    }

    protected open fun getDialogOutTransparency(): Float {
        return 0.2f
    }

    protected open fun getViews(): SparseArray<Int>? {
        return null
    }

    protected open fun getClickListener(): View.OnClickListener? {
        return null
    }

    protected open fun dismissCallback(): DismissListener? {
        return null
    }

    protected open fun getLogiclistener(): LogicListener? {
        return null
    }

    protected open fun getContentView(): View? {
        return null
    }

    protected open fun getFullScreen(): Boolean {
        return false
    }

    override fun show(manager: FragmentManager, tag: String?) {
        try {
            val mDismissed = this.javaClass.superclass?.getDeclaredField("mDismissed")
            val mShownByMe = this.javaClass.superclass?.getDeclaredField("mShownByMe")
            mDismissed?.isAccessible = true
            mShownByMe?.isAccessible = true
            mDismissed?.setBoolean(this, false)
            mShownByMe?.setBoolean(this, true)
        } catch (e: NoSuchFieldException) {
            e.printStackTrace()
        } catch (e: IllegalAccessException) {
            e.printStackTrace()
        }

        val ft = manager?.beginTransaction()
        ft?.add(this, tag)
        ft?.commitAllowingStateLoss()
    }
}